const express = require("express");
const { db } = require("../database");
// 创建路由对象，使得用户登录状态检查的中间件只作用于部分路由。
const router = express.Router();
//有没有登录
const { useAuthorization } = require("./base");
router.use(useAuthorization);
//查询会议信息
router.get("/meeting",async(req,res)=>{
  const meeting=await db.select`SELECT * FROM meetingroom`;
  res.send({
    code:200,
    message:"查询会议室成功",
    result:meeting
  })
})
//新建会议室信息
.post("/", async (req,res)=>{
const {sn,position,description}=req.body;
const meeting=await db.insert(
    "insert into meetingroom (sn,position,description) values (?, ?, ?)",
    [sn, position, description]
);
const meet=await db.findOne`select * from meetingroom where id = ${meeting}`;
res.send({
   code:200,
   message:"会议室添加成功",
   result:meet
  });
})
//修改会议室信息
.put("/put/:tid",
async(req,res)=>{
  const message= await db.findOne`select * from meetingroom where id = ${req.params.tid}`;
  if(!message){
    return res.send({
      code:-1,
      message:"该会议室信息不存在！"
    })
  }
  const{sn,position,description}=req.body;
 await db.run`update meetingroom set sn = ${sn}, position = ${position}, description = ${description} where id = ${req.params.tid}`;
 const meets=await db.findOne`select * from meetingroom where id = ${req.params.tid}`;
 res.send({
  code:200,
  message:"会议室更新成功",
  result:meets
 });
})

//删除会议室的信息
.delete("/dele/:tid",
async (req,res)=>{
  const room=
  await db.findOne`select * from meetingroom where id = ${req.params.tid}`
  if(!room){
    return res.send({
      code:-1,
      message:"该会议室信息不存在！"
    })
  }
 await db.run `delete from meetingroom where id = ${req.params.tid}`
 res.send({
  code:200,
  message:"删除成功",
 })
}
)

// 将路由作为中间件挂接在 / 根路由上。
const registerRouter = (app) => app.use("/meetingroom", router);

module.exports = { registerRouter };